'use strict';
var React = require('react');
var reactDom = require('react-dom/server');
var reactRedux = require('react-redux');
var configureStore = require('../public/javascripts/stores/index.js');
var HkfsHome = require('../public/javascripts/containers/pc/HkfsHome.jsx');
var Provider = reactRedux.Provider;
const store = configureStore();
var utils = require('../public/javascripts/common/utils');
var actions = require('../public/javascripts/actions/hkfs');
var ModelRender = require('./modelRender.jsx');
var async = require('async');
var HttpOperate = require('../nodeLibrary/HttpOperate');
var httpOperate = new HttpOperate();
var backEndUrl=require('../nodeConfig/environmentConfig');
var httpOperateForHK = new HttpOperate(backEndUrl.hkBackEndUrl);
var httpOperateForAct=new HttpOperate(backEndUrl.actBackEndurl);
var logger = require('../app').logger('userMsg');

var getHomeProductDetailByType = function (type, callBack,userId) {
    httpOperate.httpPost('/pc/productInfoCtrl/getList', {'prodTopType': type, 'curPage': 1, 'pageSize': 3, 'userId':userId?userId:null}, (result)=> {
        if (result.resultCode == '200') {
            var realResult = [];
            for (var i = 0; i < result.result.length; i++) {
                var resultItem = [
                    {id:result.result[i].id,linkId:result.result[i].parId},
                    result.result[i].name,
                    result.result[i].minYearRate == result.result[i].maxYearRate ? result.result[i].minYearRate : result.result[i].minYearRate + '～' + result.result[i].maxYearRate,
                    result.result[i].proTermStr,
                    result.result[i].sraiseAccount / 1000 + '万',
                    (result.result[i].yraiseAccount / result.result[i].financingAccount * 100).toFixed(2)
                ];
                realResult.push(resultItem);
            }
            callBack(null, realResult);
        }
        else {
            callBack(null, []);
        }
    });
};


//首页公告数据源构造
function announcementContructor(orignData){
    let result = {page: 1, totalPage: orignData.size, content: []};
    for (var i = 0; i < orignData.result.length; i++) {
        var resultItem = orignData.result[i];
        var contentItem = {
            reHref: '#',
            leftTitle: resultItem.title,
            rightTitle: resultItem.publishDate
        };
        result.content.push(contentItem);
    }
    return result;
}

//无图片新闻数据源构造
function newsContructor(orignData){
    let result = {page: 1, totalPage: orignData.size, content: []};
    for (var i = 0; i < orignData.result.length; i++) {
        var resultItem = orignData.result[i];
        var contentItem = {
            reHref: '/hkfsDetail?id='+resultItem.id,
            leftTitle: resultItem.title,
            rightTitle: resultItem.ctsStr
        };
        result.content.push(contentItem);
    }
    return result;
}


//图片新闻类表格数据源构造
function imageNewsContructor(orignData){
    let result = {page: 1, totalPage: orignData.size, content: []};
    for (var i = 0; i < orignData.result.length; i++) {
        var resultItem = orignData.result[i];
        var contentItem = {
            mainImg: resultItem.picAddress,
            href: '/hkfsDetail?id='+resultItem.id,
            title: resultItem.title,
            content: resultItem.summary,
            date: resultItem.ctsStr
        };
        result.content.push(contentItem);
    }
    return result;
}


exports.RenderFunc = (renderCallBack,userId)=> {

    async.parallel({
        hotSale: (callBack)=> {
            httpOperate.httpPost('/pc/productInfoCtrl/getList', {
                'hotSale': 1,
                'curPage': 1,
                'pageSize':99999,
                'userId':userId?userId:null
            }, (result)=> {
                    if(result.resultCode=='200') {
                        var realResult = [];
                        for (var i = 0; i < result.result.length; i++) {
                            var resultItem = {
                                id: result.result[i].id,
                                parId: result.result[i].parId,
                                mainTitle: result.result[i].label01Str == null ? '热销产品' : result.result[i].label01Str,
                                introduce: result.result[i].label01Str,
                                name: result.result[i].name,
                                profit: result.result[i].minYearRate == result.result[i].maxYearRate ? result.result[i].minYearRate : result.result[i].minYearRate + '～' + result.result[i].maxYearRate,
                                originCount: parseInt(result.result[i].subscriptionOrigin)>10000?parseInt(result.result[i].subscriptionOrigin)/10000+'万':result.result[i].subscriptionOrigin+'元',
                                term: result.result[i].proTermStr,
                                financingAmount: result.result[i].financingAccount / 10000 + '万',
                                surplusCount: result.result[i].sraiseAccount / 10000 + '万',
                                process: (result.result[i].yraiseAccount / result.result[i].financingAccount * 100).toFixed(2)
                            };
                            realResult.push(resultItem);
                        }
                        store.dispatch(actions.receivepProductItemContent(realResult));
                        callBack(null, realResult);
                    }
                    else{
                        logger.error(result);
                        callBack();
                    }

            });
        },
        homeproductDetail_1: (callBack)=> {
            getHomeProductDetailByType(2, callBack,userId);
        },
        homeproductDetail_2: (callBack)=> {
            getHomeProductDetailByType(3, callBack,userId);
        },
        homeproductDetail_3: (callBack)=> {
            getHomeProductDetailByType(4, callBack,userId);
        },
        homeproductDetail_4: (callBack)=> {

            httpOperate.httpPost('/fundInfoList', {
                'orderByType': 2,
                'fundType': 1,
                'curPage': 1,
                'pageSize': 3
            }, (result)=> {
                var realResult = [];
                for (var i = 0; i < result.length; i++) {
                    var resultItem = [
                        {id:result[i].fundCode,linkId:result[i].fundCode},
                        result[i].fundCode,
                        result[i].fundFullName,
                        result[i].dayReturn,
                        result[i].nav
                    ];
                    realResult.push(resultItem);
                }
                callBack(null, realResult);

            });
        },
        //财富动态
        dynamicsDetail:(callBack)=>{
            httpOperateForHK.httpGet('/api/article/top/DYNAMIC?curPage=0&pageSize=6',(result)=>{
                let dynamicsDetail;
                if(result.resultCode=='200'){
                    dynamicsDetail=newsContructor(result);
                    store.dispatch(actions.receiveHomeDynamicDetail(dynamicsDetail.content));
                }
                callBack();
            });

          /*  let result = JSON.parse('{     "resultCode": 0,     "msg": "成功",        "result": [{         "id": "1",               "title": "xx分公司成立",                   "ctsStr": "2016-08-09"           }, {         "id": "1",                "title": "xx分公司成立",                       "ctsStr": "2016-08-09"        }] }');
            let dynamicsDetail=newsContructor(result);
            store.dispatch(actions.receiveHomeDynamicDetail(dynamicsDetail.content));
            callBack();*/
        },
        //公告
        noticeDetails:(callBack)=>{
           /* let result = JSON.parse('{     "resultCode": 0,     "msg": "成功",       "result": [{         "id": "1",             "title": "xx分公司成立",                       "ctsStr": "2016-08-09"           }, {         "id": "1",            "title": "xx分公司成立",                    "ctsStr": "2016-08-09"            }] }');
            let noticeDetails=newsContructor(result);
            store.dispatch(actions.receiveHomeNotice(noticeDetails));
            callBack();*/

            httpOperateForAct.httpGet('/api/announcement/list/pc?curPage=0&pageSize=10',(result)=>{
                let announcement;
                if(result.resultCode=='200'){
                    announcement= announcementContructor(result);
                    store.dispatch(actions.receiveHomeNotice(announcement));
                }
                callBack();
            });
        },
        //财富新闻
        newsDetails:(callBack)=>{
            httpOperateForHK.httpGet('/api/article/top/NEWS?curPage=0&pageSize=2',(result)=>{
                let newsDetails;
                if(result.resultCode=='200'){
                    newsDetails=imageNewsContructor(result);
                    store.dispatch(actions.receiveHomeNewsDetail(newsDetails.content));
                }
                callBack();
            });
           /* let result = JSON.parse('{     "resultCode": 0,     "msg": "成功",       "result": [{         "id": "1",               "title": "xx分公司成立",                "picAddress": "aa/aa/aa",                 "summary": "恭喜河南分公司成立",              "ctsStr": "2016-08-09"          }, {         "id": "1",             "title": "xx分公司成立",               "picAddress": "aa/aa/aa",               "summary": "恭喜河南分公司成立",               "ctsStr": "2016-08-09"             }] }');
            let newsDetails=imageNewsContructor(result);
            store.dispatch(actions.receiveHomeNewsDetail(newsDetails.content));
            callBack();*/
        },
        sliderItems:(callBack)=>{
            httpOperateForHK.httpGet('/api/facade/fashview/pc',(result)=>{
                let sliderItems;
                if(result.resultCode=='200'){
                    sliderItems=result.result;
                    store.dispatch(actions.receiveHomeSliderItems(sliderItems));
                }
                callBack();
            })
        }
     /*   other: (callBack)=> {

            let sliderItems = JSON.parse('[{"imgHref":"/images/pc/banner_bg_one.png","href":"http://www.baidu.com"},{"imgHref":"/images/pc/banner_bg_one.png","href":"http://www.baidu.com"},{"imgHref":"/images/pc/banner_bg_one.png","href":"http://www.baidu.com"}]');
            let productItem=JSON.parse('[{"id":"12345","mainTitle":"新手专享","introduce":"投资特权，收益更高","name":"火柴定制一号","profit":"6.0%","originCount":"1000元","term":"30天","financingAmount":"1000万","surplusCount":"700万","process":"80"},{"id":"12345","mainTitle":"新手专享1","introduce":"投资特权，收益更高1","name":"火柴定制二号","profit":"6.0%","originCount":"1000元","term":"30天","financingAmount":"1000万","surplusCount":"700万","process":"50"},{"id":"14442345","mainTitle":"新手专享","introduce":"投资特权，收益更高","name":"火柴定制一号","profit":"6.0%","originCount":"1000元","term":"30天","financingAmount":"1000万","surplusCount":"700万","process":"80"},{"id":"1234566","mainTitle":"新手专享1","introduce":"投资特权，收益更高1","name":"火柴定制二号","profit":"6.0%","originCount":"1000元","term":"30天","financingAmount":"1000万","surplusCount":"700万","process":"50"}]');
            //固定收益
             let homeproductDetail_1=JSON.parse('[{"id":"155411","name":"火柴定制一号","profit":"6.0%","term":"30天","surplusCount":"1000万元","process":"25%"},{"id":"156411","name":"火柴定制二号","profit":"6.0%","term":"30天","surplusCount":"1000元","process":"25%"}]');
             //浮动收益
             let homeproductDetail_2=JSON.parse('[{"id":"155421","name":"火柴定制一号","profit":"6.0%","term":"30天","surplusCount":"1000万元","process":"25%"},{"id":"155413","name":"火柴定制二号","profit":"6.0%","term":"30天","surplusCount":"1000元","process":"25%"}]');
             //浮动+固定
             let homeproductDetail_3=JSON.parse('[{"id":"125411","name":"火柴定制一号","profit":"6.0%","term":"30天","surplusCount":"1000万元","process":"25%"},{"id":"195411","name":"火柴定制二号","profit":"6.0%","term":"30天","surplusCount":"1000元","process":"25%"}]');
             //公募基金
             let homeproductDetail_4=JSON.parse('[{"id":"755411","name":"基金测试1","profit":"-6.0%","term":"30天","surplusCount":"1000万元"},{"id":"1365411","name":"基金测试2","profit":"6.0%","term":"30天","surplusCount":"1000元"}]');
             //产品集合
             let homeproductDetail={homeproductDetail_1:homeproductDetail_1,homeproductDetail_2:homeproductDetail_2,homeproductDetail_3:homeproductDetail_3,homeproductDetail_4:homeproductDetail_4};
            let dynamicsDetail = JSON.parse('[{"reHref":"/dsf/sdf/sdf","leftTitle":"测试测试长度分数分数分数1","rightTitle":"2016-05-11"},{"reHref":"/dsf/sdf/sdf","leftTitle":"测试测试长度分数分数分数12","rightTitle":"2016-05-11"},{"reHref":"/dsf/sdf/sdf","leftTitle":"测试测试长度分数分数分数13","rightTitle":"2016-05-11"},{"reHref":"/dsf/sdf/sdf","leftTitle":"测试测试长度分数分数分数13","rightTitle":"2016-05-11"},{"reHref":"/dsf/sdf/sdf","leftTitle":"测试测试长度分数分数分数12","rightTitle":"2016-05-11"},{"reHref":"/dsf/sdf/sdf","leftTitle":"测试测试长度分数分数分数12","rightTitle":"2016-05-11"}]');
            let newsDetails = JSON.parse('[{"mainImg":"/images/pc/content_icon_financial_hover.png","href":"http://www.baidu.com","title":"新闻测试新闻测试新闻测试新闻测试1","content":"新闻测试新闻测试新闻测试新闻测试1新闻测试新闻测试新闻测试新闻测试1新闻测试新闻测试新闻测试新闻测试1新闻测试新闻测试新","date":"2016-05-11"},{"mainImg":"/images/pc/content_icon_financial_hover.png","href":"http://www.baidu.com","title":"新闻测试新闻测试新闻测试新闻测试2","content":"新闻测试新闻测试新闻测试新闻测试1新闻测试新闻测试新闻测试新闻测试1新闻测试新闻测试新闻测试新闻测试1新闻测试新闻","date":"2016-05-11"}]');
            let noticeDetails=JSON.parse('{"page":1,"totalPage":10,"content":[{"reHref":"/dsf/sdf/sdf","leftTitle":"测试测试长度分数分数分数1","rightTitle":"2016-05-11"},{"reHref":"/dsf/sdf/sdf","leftTitle":"测试测试长度分数分数分数12","rightTitle":"2016-05-11"},{"reHref":"/dsf/sdf/sdf","leftTitle":"测试测试长度分数分数分数13","rightTitle":"2016-05-11"},{"reHref":"/dsf/sdf/sdf","leftTitle":"测试测试长度分数分数分数13","rightTitle":"2016-05-11"},{"reHref":"/dsf/sdf/sdf","leftTitle":"测试测试长度分数分数分数12","rightTitle":"2016-05-11"}]}');


             store.dispatch(actions.receivepHomeProductDetailContent(homeproductDetail));
            store.dispatch(actions.receiveHomeNewsDetail(newsDetails));
            store.dispatch(actions.receiveHomeDynamicDetail(dynamicsDetail));
            store.dispatch(actions.receiveHomeSliderItems(sliderItems));
            store.dispatch(actions.receiveHomeNotice(noticeDetails));
            callBack();
        }*/
    }, (err, results)=> {
        for (var item in results) {
            if (results[item] === undefined) {
                delete results[item];
            }
        }
        store.dispatch(actions.receivepHomeProductDetailContent(results));
        if (renderCallBack) {
            var main = reactDom.renderToString(
                <Provider store={store}>
                    <HkfsHome/>
                </Provider>
            );
            var modelRender = new ModelRender();
            var initializeStore = JSON.stringify(store.getState());
            renderCallBack(modelRender.headerRender(), modelRender.barRender(), modelRender.footerRender(), main, initializeStore);
        }
    });

};

